/**
 * @desc: 退货物流单号管理
 * @author: fj
 */
import { useState, useEffect, useMemo } from 'react';
import FormContent from './component/FormContent';
import OperaBtnRender from '@/components/OperaBtnRender';
import TableRender from '@/components/TableRender';
import EditNoteModal from './component/EditNoteModal';
import FormRender from '@/components/FormRender';
import Iconfont from "@/components/IconFont";
import { useResize } from '@/hooks/useResize';
import { getFormItem, srcMap } from './config.js';
import ExportModal from './component/ExportModal';
import { queryPageList, createExportTask } from './service';
import { Popover, Typography } from "antd";
import styles from './index.module.less';
import moment from 'moment';

const { Paragraph } = Typography;

const ReceiptReturn = () => {
  const [data, setData] = useState([]);
  const [query, setQuery] = useState({});
  const [visible, setVisible] = useState(false); //备注弹窗visible
  const [record, setRecord] = useState({}); //单行选择的数据
  const [taskId, setTaskId] = useState(""); //导出任务id
  const [exportVisible, setExportVisible] = useState(false); //导出visible
  //分页数据
  const [pagination, setPagination] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  });

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem();
  }, [])

  const columns = [
    {
      title: "物流公司",
      code: "logisticsCompany",
      width: 100
    },
    {
      title: "物流单号",
      code: "logisticsNo",
      width: 100,
      render: (text, record) => {
        return (
          <div className="myParagraph">
            <Paragraph copyable={{ text: text }}>{text}</Paragraph>
          </div>
        );
      }
    },
    {
      title: "包裹重量",
      code: "weight",
      width: 100
    },
    {
      title: "数据获取方式",
      code: "src",
      width: 120,
      render: (text, record) => <span>{srcMap[text]}</span>
    },
    {
      title: "创建人",
      code: "createAccount",
      width: 100
    },
    {
      title: "创建时间",
      code: "createTime",
      width: 150
    },
    {
      title: "备注",
      code: "note",
      width: 130,
      render: (text, record) => {
        return (
          <div style={{ display: "flex" }}>
            <Popover content={<div className="custom-ant-popver-content">{text || ""}</div>}>
              <span className="textOverflowMultiTwo">{text || ""}</span>
            </Popover>
            <div onClick={() => handleEditNote(record)}>
              <Iconfont
                className="common-color2"
                style={{
                  fontSize: "14px",
                  marginLeft: "8px",
                  // marginTop: '6px',
                  marginRight: "46px"
                }}
                type="iconbianji1"
              />
            </div>
          </div>
        );
      }
    }
  ];

  useEffect(() => {
    getPageList(query, pagination);
  }, [query]);

  // 查询退货物流单号列表接口
  const getPageList = async (query, pagination) => {
    START_LOADING();
    setData([]);
    const { success, data = {} } = await queryPageList({
      ...query,
      current: pagination.current,
      size: pagination.pageSize,
      timeStart: query.time
        ? moment(query.time[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      timeEnd: query.time
        ? moment(query.time[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      time: undefined,
    });
    if (success) {
      const { records = [], total = 0 } = data;
      setData(records);
      setPagination({
        ...pagination,
        total,
      });
    }
    END_LOADING();
  };

  //创建导出任务
  const handleCreateExportTask = async params => {
    START_LOADING();
    const { data, success } = await createExportTask(params);
    if (success) {
      setTaskId(data);
      setExportVisible(true);
    }
    END_LOADING();
  };

  //导出
  const handleExport = () => {
    const params = {
      businessParam: {},
      taskType: 4006
    };
    const businessParam = { ...query };
    if (businessParam.time) {
      businessParam.timeStart = query.time
        ? moment(query.time[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined;
      businessParam.timeEnd = query.time
        ? moment(query.time[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined;
      businessParam.time = undefined;
    }
    params.businessParam = JSON.stringify(businessParam);
    handleCreateExportTask(params);
  };

  //导出进度弹窗
  const ExportModalProps = {
    taskId,
    visible: exportVisible,
    handleCancel() {
      setExportVisible(false);
      setTaskId("");
    }
  };

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'receipt-return-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setQuery(val);
    },
    clickReset() {
      setQuery({});
    },
  }

  //新增区域
  const FormContentProps = {
    handleOk() {
      getPageList(query, pagination);
    },
  };

  const handleEditNote = (record) => {
    setRecord(record);
    setVisible(true);
  }

  //表格组件
  const TableRenderProps = {
    data,
    columns,
		rowKey: "id",
    style: {
      height: `calc(100vh - ${headerHeight + 224}px)`
    },
    pageConfig: {
      pages: pagination,
      handlePageSize(current, pageSize) {
        setPagination({
          ...pagination,
          current,
          pageSize,
        });
        getPageList(query, { ...pagination, current, pageSize });
      }
    }
  }

  //修改备注
  const EditNoteModalProps = {
    visible,
    record,
    handleOk() {
      getPageList(query, pagination);
      setVisible(false);
      setRecord({});
    },
    handleCancel() {
      setVisible(false);
      setRecord({});
    },
  };


  //操作按钮
  const btnArr = [
    { elType: 'button', text: '表格导出', onClick: handleExport }
  ]

  return (
    <>
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap' style={{ height: `calc(100vh - ${headerHeight + 112}px)`, overflow: 'auto'}}>
        <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
        <div className={styles.contentBox}>
          <div className={styles.contentLeft}>
            <FormContent {...FormContentProps} />
          </div>
          <div className={styles.contentRight}>
            <TableRender {...TableRenderProps} />
          </div>
        </div>
      </div>
      {visible && <EditNoteModal {...EditNoteModalProps} />}
      {exportVisible && <ExportModal {...ExportModalProps} />}
    </>
  );
};

export default ReceiptReturn;
